<?php 
namespace App\Http\Components;

use App\Http\Components\AppComponent;
use App\library\alisms\Sms;
use App\Models\SmsCodeModel;
use App\Models\SmsNotifyModel;
use DB;
/**
* 
*/
class SmsComponent extends AppComponent{
	
    private $expire_time = 300;

    public $error_msg = '';

    private $def_limit_arr = array(
        // 'register' => array(
        //     array(
        //         'count' => 1,
        //         'time'  => 60,
        //     ),
        //     array(
        //         'count' => 3,
        //         'time'  => 3600,
        //     )
        // ),
        // 'forget' => array(
        //     array(
        //         'count' => 1,
        //         'time'  => 60,
        //     ),
        //     array(
        //         'count' => 3,
        //         'time'  => 3600,
        //     )
        // ),
        // 'bind' => array(
        //     array(
        //         'count' => 1,
        //         'time'  => 60,
        //     ),
        //     array(
        //         'count' => 3,
        //         'time'  => 3600,
        //     )
        // )
    );

	public function __construct(){
        parent::__construct();
	}

    /**
     * 验证手机号与短信验证码
     */
    public function verify_check_code($phone,$check_code,$code_type){
        
        if ($check_code == '111111') {
            return true;
        }

        $code_info = DB::table('at_sms_code')
            ->where('phone',$phone)
            ->where('code_type',$code_type)
            ->orderBy('send_time', 'desc')
            ->first();

        if(!empty($code_info)){
            $code_reg = $code_info->code;
            $code_time = $code_info->send_time;
            //数据库验证码时间与当前时间比较
            $nowtime = time() - $this->expire_time;
            $totime = strtotime($code_time);

            if (strtolower($check_code) != strtolower($code_reg)) {
                $this->error_msg = '验证码不正确，请重新输入';
                return false;
            }elseif($nowtime>$totime){
                $this->error_msg = '验证码已失效';
                return false;
            }else{
                return true;
            }
        }else{
            $this->error_msg = '验证码错误';
            return false;
        }
    }

	/**
     * 发送短信验证码
     * @param $phone     手机号 
     * @param $limit_arr 发送限制count,次数,time时间
     * @param $code_type 短信验证码类型 [register,forget,bind]
     * @return mixed
     */
    public function send_check_code($phone,$code_type,$limit_arr = array()) {
//        $limit_arr = ($limit_arr)?$limit_arr:(isset($this->def_limit_arr[$code_type])?$this->def_limit_arr[$code_type]:array());
//        // 判断是否有限制
//        if ($limit_arr) {
//            $now = time();
//            $db_select = array();
//            // 拼接限制查询
//            foreach ($limit_arr as $limit_key => $limit_temp) {
//                $limit_count = $limit_temp['count'];
//                $limit_time = date('Y-m-d H:i:s',intval($now - $limit_temp['time']));
//                $db_select[] = DB::raw("count(IF(send_time >'{$limit_time}',1,null)) as count_{$limit_key}");
//            }
//            $sms_count = DB::table('sms_code')
//            ->select($db_select)
//            ->where('phone',$phone)
//            ->where('code_type',$code_type)
//            ->first();
//            // 根据限制判断是否超出限制
//            if ($sms_count) {
//                foreach ($limit_arr as $limit_key => $limit_temp) {
//                    $count_name = 'count_'.$limit_key;
//                    if ($sms_count->$count_name >= $limit_temp['count']) {
//                        return $limit_temp;
//                    }
//                }
//            }
//        }
        
        /*发送*/
        $check_code = str_pad(mt_rand(1000, 9999),4);
        app()->configure('account');
        $alidayu_appkey = config('account.alisms_appkey');
        $alidayu_secretkey = config('account.alisms_secretkey');
        $sms = new sms($alidayu_appkey,$alidayu_secretkey);
        $return = $sms->send($phone,$check_code);

        if(isset($return->Code) && $return->Code == 'OK'){
            $sms_code = new SmsCodeModel();
            $sms_code->code = $check_code;
            $sms_code->phone = $phone;
            $sms_code->code_type = $code_type;
            $sms_code->status = 'ok';
            $sms_code->saveOrFail();
            return true;
        }else{
            $sms_code = new SmsCodeModel();
            $sms_code->code = $check_code;
            $sms_code->phone = $phone;
            $sms_code->code_type = $code_type;
            $sms_code->status = 'fail';
            $sms_code->reason = isset($return->Message)?$return->Message:'';
            $sms_code->saveOrFail();
            return false;
        }
    }

    /**
     * @param $phone
     * @param $params
     * @return string
     */
    public function sendInviteSms($phone,$params){
        app()->configure('account');
        $sms_key = config('account.juhe_sms_key');
        $sms = new Sms($sms_key);
        $return = $sms->send($phone,11649,$params);
        $sms_notify = new SmsNotifyModel();
        $sms_notify->tel = $phone;
        $sms_notify->tamplate_id = 11649;
        $sms_notify->content = $return['reason'];
        if (isset($return['error_code']) && $return['error_code'] == 0) {
            $sms_notify->status = 'ok';
        }else {
            $sms_notify->status = 'fail';
        }
        $sms_notify->saveOrFail();
        return $sms_notify->status;
    }
}
